package demo02;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class IOServer {
    // 使用线程池来处理客户端请求，实现并发
    private static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(200);

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            System.out.println("传统 IO 服务器已启动，监听端口 8080...");

            while (true) {
                // 接受新的客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("接受了新的传统 IO 连接：" + clientSocket.getInetAddress());

                // 将客户端请求提交到线程池中处理
                THREAD_POOL.execute(() -> {
                    try (
                        InputStream in = clientSocket.getInputStream();
                        OutputStream out = clientSocket.getOutputStream()
                    ) {
                        byte[] buffer = new byte[1024];
                        int bytesRead = in.read(buffer);
                        if (bytesRead != -1) {
                            // 将接收到的数据回写给客户端
                            out.write(buffer, 0, bytesRead);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            THREAD_POOL.shutdown();
        }
    }
}